/*
 * @Author: wangjq4214
 * @Date: 2022-04-17 10:39:02
 * @LastEditTime: 2022-05-24 21:08:30
 * @LastEditors: wangjq4214
 */
package main

import (
	"context"
	"time"

	"gitee.com/wangjq4214/schedule/proto"
	pb "gitee.com/wangjq4214/schedule/proto/leader"
)

type Server struct {
	pb.UnimplementedLeaderServeServer

	registerChan chan RegisterBody
	finishChan   chan Task
}

func NewServe(registerChan chan RegisterBody, finishChan chan Task) *Server {
	return &Server{
		registerChan: registerChan,
		finishChan:   finishChan,
	}
}

func (s *Server) Register(ctx context.Context, in *pb.RegisterReq) (*pb.RegisterRes, error) {
	tmp := make([]*Task, 0)
	for _, item := range in.GetTask() {
		tmp = append(tmp, &Task{
			UUID:       item.GetID(),
			CPU:        int(item.GetCPU()),
			Storage:    int(item.GetStorage()),
			Time:       item.GetTime(),
			Need:       item.GetNeed(),
			CommitTime: time.Now().Unix(),
			Position: DataPosition{
				ID: item.GetPosition().GetID(),
				IP: item.GetPosition().GetIP(),
			},
		})
	}

	s.registerChan <- RegisterBody{
		IP:           in.GetIP(),
		CPUTotal:     in.GetCPUTotal(),
		CPUMax:       in.GetCPUMax(),
		CPUUsing:     in.GetCPUUsing(),
		CPUWait:      in.GetCPUWait(),
		StorageTotal: in.GetStorageTotal(),
		StorageUsing: in.GetStorageUsing(),
		Time:         in.GetTime(),
		Task:         tmp,
	}

	return &pb.RegisterRes{
		Status: &proto.Status{
			Code: 0,
			Msg:  "success",
		},
	}, nil
}

func (s *Server) ReportTaskStatus(ctx context.Context, in *pb.ReportTaskStatusReq) (*pb.ReportTaskStatusRes, error) {
	s.finishChan <- Task{
		UUID:        in.GetID(),
		FinishTime:  in.GetFinishTime(),
		StartTime:   in.GetStartTime(),
		ReceiveTime: in.GetReceiveTime(),
		ReadyTime:   in.GetReadyTime(),
	}

	return &pb.ReportTaskStatusRes{
		Status: &proto.Status{
			Code: 0,
			Msg:  "success",
		},
	}, nil
}
